package dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import dao.interf.IBaseDao;

@Transactional
@SuppressWarnings("unchecked")
public class BaseDao<T> implements IBaseDao<T> {
	private String TABLENAME = "";
	private String POJOCLASS = "";
	private Class<T> clazz;
	@Resource
	private SessionFactory sessionFactory;

	public BaseDao() {
		ParameterizedType type = (ParameterizedType) this.getClass()
				.getGenericSuperclass();
		this.clazz = (Class<T>) type.getActualTypeArguments()[0];
		this.TABLENAME = this.clazz.getSimpleName();
	}

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	//增加
	public String add(T entity) {
		Serializable id = getSession().save(entity);
		return id.toString();
	}
	
	//删除
	public void deleteById(Integer id) {
		Object object = (Object) getSession().get(clazz, id);
		getSession().delete(object);
	}
	
	//修改
	public void edit(T entity) {
		getSession().update(entity);
	}
	
	
	//查找
	public T getById(Integer id) {
		return (T) getSession().get(clazz, id);
	}
	
	public T getByProperty(String pName, String pValue) {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from " + TABLENAME + " as model where model." + pName + " = ?");
		query.setString(0, pValue);
		T t = (T)query.uniqueResult();
		return t;
	}
	
	public List<T> getListByProperty(String pName, String pValue) {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from " + TABLENAME + " as model where model." + pName + " = ?");
		query.setString(0, pValue);
		List<T> list = query.list();
		return list;
	}
	
	public List<T> getAll() {
		return getSession().createQuery("from " + clazz.getSimpleName()).list();
	}

	
}

